package com.sleep.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sleep.blog.dao.mapper.ArticleMapper;
import com.sleep.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Sleep-6000
 * @date 2021/9/28
 */
@Component
public class ThreadService {

    /**
     * 希望此操作在线程池执行，不会影响原有的主线程
     *
     * @param articleMapper articleMapper
     * @param article       article
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        //再设置一个 为了在多线程的环境下保证线程安全
        updateWrapper.eq(Article::getViewCounts, viewCounts);
        articleMapper.update(articleUpdate, updateWrapper);

        try {
            Thread.sleep(5000);
            System.out.println("阅读数更新成功....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
